package com.yihen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yihen.bean.User;
import com.yihen.dto.Result;
import com.yihen.mapper.UserMapper;
import com.yihen.service.UserService;
import com.yihen.utils.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Result register(User user) {
        // 判断用户是否存在
        if (isRegister(user.getUsername())) {
            return Result.error("用户已经存在");
        }
        // 生成用户id
        Long id = IdWorker.getId();
        user.setId(id);
        userMapper.insert(user);
        log.debug("用户注册成功，用户id为：{}", id);
        return Result.ok("注册成功",null);
    }

    @Override
    public Result login(User user) {
        User user1 = checkLogin(user);
        if (Objects.isNull(user1)) {
            return Result.error("用户名或密码错误");
        }
        log.debug("用户登录成功，用户id为：{}", user1.getId());
        return Result.ok("登录成功", user1.getId().toString());
    }

    // 判断用户名是否已经注册
    private boolean isRegister(String username) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username);
        return !Objects.isNull(userMapper.selectOne(userQueryWrapper)) ;
    }

    // 验证登陆信息
    private User checkLogin(User user) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", user.getUsername())
                .eq("password", user.getPassword());
        return userMapper.selectOne(userQueryWrapper);
    }
}
